import { observe } from "../instance/state";
import { arrayMethods } from "./array";
import Dep from "./dep";

export class Observer {
  constructor(data) {
    this.dep = new Dep();

    //增加observer的实例标识，意味着是否已经实例化了
    Object.defineProperty(data, "__ob__", {
      value: this,
      enumerable: false,
    });

    //判断是否为数组
    if (Array.isArray(data)) {
      data.__proto__ = arrayMethods; //7个变异方法 重写
      this.observeArray(data);
    } else {
      this.walk(data);
    }
  }
  walk(data) {
    for (const key in data) {
      if (Object.hasOwnProperty.call(data, key)) {
        const value = data[key];
        defineReactive(data, key, value);
      }
    }
  }
  observeArray(arr) {
    arr.forEach((item) => observe(item));
  }
}

export function defineReactive(target, key, value) {
  if (arguments.length === 2) {
    value = target[key];
  }
  const childOb = observe(value); //递归
  const dep = new Dep();
  Object.defineProperty(target, key, {
    configurable: true,
    enumerable: true,
    get() {
        console.log("获取数据",target, key, value);
      if (Dep.target) {
        dep.depend();
        if (childOb) {
          childOb.dep.depend();
          //数组里面还可以嵌套数组，也需要收集依赖
          dependArray(value);
        }
      }
      return value;
    },
    set(newValue) {
      //   console.log("设置数据");
      if (newValue === value) return;
      value = newValue;
      debugger
      dep.notify();
    },
  });
}

function dependArray(value) {
  if (!Array.isArray(value)) return;
  value.forEach((e) => {
    if (e && e.__ob__) {
      e.__ob__.dep.depend();
    }

    if (Array.isArray(e)) {
      dependArray(e);
    }
  });
}
